package com.sinosoft.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import org.nutz.lang.Files;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import sun.util.logging.resources.logging;
/**
 * zip工具类
 * @author unhappydepig
 *
 */
public class ZipUtil {
	private static Log log = Logs.get();
	static final int BUFFER = 8192;
	/**
	 * 文件压缩
	 * @param zipFile
	 * @param srcPathName
	 * @throws IOException 
	 */
	public static void zip(File zipFile,String srcPathName) throws IOException {
		if (!zipFile.exists()){
			Files.createNewFile(zipFile);
		}
		File file = new File(srcPathName);
		if (!file.exists()){
			Files.createNewFile(file);
		}
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(zipFile);
			CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,
					new CRC32());
			ZipOutputStream out = new ZipOutputStream(cos);
			String basedir = "";
			zip(file, out, basedir);
			out.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	   /** 
	    * 解压缩zip包
	    * @param zipFilePath zip文件路径
	    * @param targetPath 解压缩到的位置，如果为null或空字符串则默认解压缩到跟zip包同目录跟zip包同名的文件夹下
	    * @throws IOException
	    */
	   public static void unzip(String zipFilePath, String targetPath)
	           throws IOException {
	       OutputStream os = null;
	       InputStream is = null;
	       ZipFile zipFile = null;
	       try {
	           zipFile = new ZipFile(zipFilePath);
	           String directoryPath = "";
	           if (null == targetPath || "".equals(targetPath)) {
	               directoryPath = zipFilePath.substring(0, zipFilePath
	                       .lastIndexOf("."));
	           } else {
	               directoryPath = targetPath;
	           }
	           Enumeration entryEnum = zipFile.getEntries();
	           if (null != entryEnum) {
	               ZipEntry zipEntry = null;
	               while (entryEnum.hasMoreElements()) {
	                   zipEntry = (ZipEntry) entryEnum.nextElement();
	                   if (zipEntry.isDirectory()) {
	                       directoryPath = directoryPath + File.separator+ zipEntry.getName();
	                       continue;
	                   }
	                   if (zipEntry.getSize() > 0) {
	                       // 文件
	                       File targetFile = new File(directoryPath+ File.separator + zipEntry.getName());
		               		if (!targetFile.exists()){
		               			Files.createNewFile(targetFile);
		               		}
	                       os = new BufferedOutputStream(new FileOutputStream(
	                               targetFile));
	                       is = zipFile.getInputStream(zipEntry);
	                       byte[] buffer = new byte[4096];
	                       int readLen = 0;
	                       while ((readLen = is.read(buffer, 0, 4096)) >= 0) {
	                           os.write(buffer, 0, readLen);
	                       }
	                       os.flush();
	                       os.close();
	                   } else {
	                       // 文件
	                       File targetFile = new File(directoryPath
	                               + File.separator + zipEntry.getName());
		               		if (!targetFile.exists()){
		               			Files.createNewFile(targetFile);
		               		}
	                   }
	               }
	           }
	       } catch (IOException ex) {
	           throw ex;
	       } finally {
	           if(null != zipFile){
	               zipFile = null;
	           }
	           if (null != is) {
	               is.close();
	           }
	           if (null != os) {
	               os.close();
	           }
	       }
	   }	
	private static void zip(File file, ZipOutputStream out, String basedir) {
		/* 判断是目录还是文件 */
		log.info("压缩：" + basedir + file.getName());
		if (file.isDirectory()) {
			zipDirectory(file, out, basedir);
		} else {
			zipFile(file, out, basedir);
		}
	}

	/** 压缩一个目录 */
	private static void zipDirectory(File dir, ZipOutputStream out, String basedir) {
		if (!dir.exists())
			return;

		File[] files = dir.listFiles();
		for (int i = 0; i < files.length; i++) {
			/* 递归 */
			zip(files[i], out, basedir + dir.getName() + "/");
		}
	}

	/** 压缩一个文件 */
	private static void zipFile(File file, ZipOutputStream out, String basedir) {
		if (!file.exists()) {
			return;
		}
		try {
			BufferedInputStream bis = new BufferedInputStream(
					new FileInputStream(file));
			ZipEntry entry = new ZipEntry(basedir + file.getName());
			out.putNextEntry(entry);
			int count;
			byte data[] = new byte[BUFFER];
			while ((count = bis.read(data, 0, BUFFER)) != -1) {
				out.write(data, 0, count);
			}
			bis.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
